<template>
  <div class="home-page" v-loading="loading" element-loading-text="加载中...">
    <el-row :gutter="20">
      <!-- 左侧：学员信息 -->
      <el-col :xs="24" :lg="6">
        <el-card class="student-info-card">
          <div class="student-avatar">
            <el-avatar 
              :size="100" 
              :src="userInfo.avatar"
            ></el-avatar>
          </div>
          
          <h2 class="student-name">{{ userInfo.name }}</h2>
          
          <div class="info-list">
            <div class="info-item">
              <div class="info-icon">
                <i class="el-icon-phone"></i>
              </div>
              <div class="info-content">
                <p class="info-label">联系电话</p>
                <p class="info-value">{{ maskPhone(userInfo.phone) }}</p>
              </div>
            </div>
            
            <div class="info-item">
              <div class="info-icon">
                <i class="el-icon-postcard"></i>
              </div>
              <div class="info-content">
                <p class="info-label">证件号码</p>
                <p class="info-value">{{ maskIdCard(userInfo.idCard) }}</p>
              </div>
            </div>
          </div>
          
          <el-button 
            type="primary" 
            class="edit-profile-btn"
            @click="$router.push('/profile')"
          >
            <i class="el-icon-edit"></i> 编辑个人信息
          </el-button>
        </el-card>
      </el-col>
      
      <!-- 右侧：课程列表和实训成绩 -->
      <el-col :xs="24" :lg="18">
        <!-- 我的课程 -->
        <el-card class="section-card">
          <div slot="header" class="card-header">
            <span>我的课程</span>
            <el-button type="text" @click="$router.push('/courses')">
              查看全部 <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
          
          <div class="course-list">
            <el-empty 
              v-if="!loading && courseList.length === 0" 
              description="暂无课程数据"
            ></el-empty>
            <div 
              v-for="course in courseList" 
              :key="course.id"
              class="course-item"
            >
              <div class="course-info">
                <h3 class="course-title">{{ course.name }}</h3>
              </div>
              
              <div class="course-progress">
                <div class="progress-item">
                  <div class="progress-header">
                    <span>知识学习进度</span>
                    <span class="progress-value">{{ course.learningProgress }}%</span>
                  </div>
                  <el-progress 
                    :percentage="course.learningProgress" 
                    :show-text="false"
                    color="#165DFF"
                  ></el-progress>
                </div>
                
                <div class="progress-item">
                  <div class="progress-header">
                    <span>测验进度 ({{ course.completedQuizzes }}/{{ course.totalQuizzes }})</span>
                    <span class="progress-value">{{ course.quizProgress }}%</span>
                  </div>
                  <el-progress 
                    :percentage="course.quizProgress" 
                    :show-text="false"
                    color="#FF7D00"
                  ></el-progress>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        
        <!-- 实训成绩 -->
        <el-card class="section-card mt-20">
          <div slot="header" class="card-header">
            <span>实训成绩</span>
            <el-button type="text" @click="$router.push('/training')">
              查看全部 <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
          
          <el-table 
            :data="trainingList"
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa' }"
          >
            <el-table-column prop="name" label="实训名称" min-width="200"></el-table-column>
            <el-table-column label="状态" width="120" align="center">
              <template slot-scope="scope">
                <el-tag 
                  :type="scope.row.status === 'completed' ? 'success' : 'primary'"
                  size="small"
                >
                  {{ scope.row.status === 'completed' ? '已完成' : '进行中' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="score" label="成绩" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.score || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template slot-scope="scope">
                <el-button 
                  v-if="scope.row.status === 'completed'"
                  type="text" 
                  size="small"
                >
                  查看回放
                </el-button>
                <el-button 
                  v-else
                  type="text" 
                  size="small"
                >
                  继续实训
                </el-button>
                <el-button 
                  type="text" 
                  size="small"
                  :disabled="scope.row.status !== 'completed'"
                >
                  成绩报告
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getAvatarUrl, parseProgress } from '@/utils/url'

export default {
  name: 'Home',
  data() {
    return {
      userInfo: {
        name: '',
        avatar: '',
        phone: '',
        idCard: ''
      },
      courseList: [],
      trainingList: [],
      loading: false
    }
  },
  mounted() {
    this.getHomeData()
    // 注意：Home.vue 不需要监听 userInfoUpdated 事件
    // 因为 Home.vue 是数据的来源，它会触发事件通知其他组件（如 Layout）
    // 如果监听自己的事件会导致循环调用
  },
  methods: {
    // 获取首页聚合数据
    async getHomeData() {
      this.loading = true
      try {
        const res = await this.$api.home.getHomeData()
        
        // 后端返回结构: { code: 200, message: "success", data: { user_info, course_list, virtual_classroom_scores } }
        // 响应拦截器应该已经提取了 data 字段，所以 res 就是 data 对象
        // 但为了兼容，同时检查 res.data 和 res
        const data = res.data || res
        
        // 处理用户信息
        if (data && data.user_info) {
          
          // 保存原始头像URL到localStorage（不处理为完整URL，让Layout组件自己处理）
          const rawAvatar = data.user_info.avatar || ''
          
          // 用于页面显示的完整URL
          const displayAvatar = getAvatarUrl(data.user_info.avatar)
          
          this.userInfo = {
            name: data.user_info.name || '',
            username: data.user_info.username || '',
            phone: data.user_info.phone || '',
            avatar: displayAvatar,
            idCard: data.user_info.id_card || ''
          }
          
          // 保存到localStorage（保存原始URL，让Layout组件自己处理）
          const userInfoToSave = {
            name: data.user_info.name || '',
            username: data.user_info.username || '',
            phone: data.user_info.phone || '',
            avatar: rawAvatar, // 保存原始URL
            id_card: data.user_info.id_card || ''
          }
          localStorage.setItem('userInfo', JSON.stringify(userInfoToSave))
          
          // 触发事件通知Layout组件更新
          window.dispatchEvent(new CustomEvent('userInfoUpdated'))
        }
        
        // 处理课程列表
        if (data && data.course_list && data.course_list.length > 0) {
          this.courseList = data.course_list.map(course => ({
            id: course.id,
            name: course.name,
            number: course.code || '',
            learningProgress: parseProgress(course.knowledge_progress),
            completedQuizzes: course.papers ? course.papers.length : 0,
            totalQuizzes: course.papers ? course.papers.length : 0,
            quizProgress: parseProgress(course.paper_progress)
          }))
        }
        
        // 处理虚拟教室成绩列表
        if (data && data.virtual_classroom_scores && data.virtual_classroom_scores.length > 0) {
          this.trainingList = data.virtual_classroom_scores.map(training => ({
            id: training.id,
            name: training.project_name,
            // 后端返回数字: 1=已完成, 0=进行中
            status: training.status === 1 ? 'completed' : 'active',
            score: training.score
          }))
        }
      } catch (error) {
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    maskPhone(phone) {
      if (!phone) return ''
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    },
    maskIdCard(idCard) {
      if (!idCard) return ''
      return idCard.replace(/(\d{3})\d{8}(\d{4})/, '$1********$2')
    }
  }
}
</script>

<style scoped>
.home-page {
  padding: 20px 0;
}

.student-info-card {
  text-align: center;
  position: sticky;
  top: 80px;
}

.student-avatar {
  margin: 20px 0;
}

.student-name {
  font-size: 20px;
  font-weight: bold;
  color: #304156;
  margin: 16px 0;
}

.info-list {
  margin: 24px 0;
  text-align: left;
}

.info-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.info-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #e6f4ff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #165DFF;
  margin-right: 12px;
  flex-shrink: 0;
}

.info-content {
  flex: 1;
}

.info-label {
  font-size: 12px;
  color: #86909C;
  margin-bottom: 4px;
}

.info-value {
  font-size: 14px;
  color: #304156;
}

.edit-profile-btn {
  width: 100%;
  margin-top: 16px;
}

.section-card {
  margin-bottom: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
}

.course-list {
  border-top: 1px solid #EBEEF5;
  margin-top: -16px;
}

.course-list:first-child {
  border-top: none;
}

.course-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #EBEEF5;
}

.course-item:hover {
  background: #f5f7fa;
  margin: 0 -20px;
  padding: 20px;
}

.course-info h3 {
  font-size: 16px;
  color: #304156;
  margin-bottom: 8px;
}

.course-number {
  font-size: 13px;
  color: #86909C;
}

.course-progress {
  min-width: 280px;
  flex-shrink: 0;
}

.progress-item {
  margin-bottom: 16px;
}

.progress-item:last-child {
  margin-bottom: 0;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  margin-bottom: 8px;
}

.progress-value {
  font-weight: 500;
  color: #304156;
}

@media (max-width: 992px) {
  .course-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .course-progress {
    width: 100%;
    margin-top: 16px;
  }
}
</style>
